package com.hand.wfive.loginAndVip;

import android.util.Base64;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class RsaUtils {

    /**
     * return值解密私钥
     */
    public static final String returnDecryptPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCjgz+TZKppkyL1nd/4me/kF1YEK2r3kmGKFSDu6gAuXftB4m53tAxBhdljNAEKyGsc34ly8i8O3grX4fjMpa+HmWP1YMF01IGhmTZh8gchV6rbtJ0AK9QGVmp+wUcC3lnRDGyYwGKdgpJdCOOuI7XgJSnp8Vezywo9JtM09dxOsD5Dd8v69ynHuokxwizwcw5TaAEGyQqiX/ibYQgnDClXCZxUncVEeCn/ls6X6DfqjAv9kaPuYNn7JLygznYlYLAHiQuUEBW+we127kH2atgj7BmAxA6lH0UgtidnZII93bLv50i+hRKRUv7KAQi0/im+4T9lrD2CQUOzBJhhzJTfAgMBAAECggEATfuSnqEsBR3/VlTtNIt2NbpLc8GhSmGt00UwZ8GCRJrd8hYjyUM9dSJ5Ay8SMCpVq3eQ/hkzCEwtr7g+CJwckvc9DRIQMcAH8yI3JY9ghy5gdlg1aJd+j2c3cyyKyXtyKplaUZ+vaJ+VXnmW3L57R2NyEfjgcwcq4u9ZW7DGWWBA0d8ckxZeLP9r0sMzF3+mNEioSod4TDYnsAPGIOyWx2miQoBx05ho6i+uuC7Z+grmM4N+W5s1UKnh9EZ+bqIpptwEx7ZdaOXtOT6MBMiyjs9Sr6/9wz8DuoXcUIbzYYP6jf9ZCw9kWlZjc103y84gQ9tOJXmKIt0gCy27Jb4oQQKBgQDgiY9k6VpbufYrE7scTZ7bAljVeZPLB22gC3P6tKqMGMs2kqsARU5Xlb71i+u7CXMadKK79ywFS/LT/OYZDU/NHHV8bGBpdOVF08v3EommSilDdJJ0cwxu/Z09urLe0ClzlaQUo1AZWy+br2ftzlThBmQvDHr1L3ZVwdzpSwMPvQKBgQC6bKgBfU8Vcl19ORjGHSOAqua0Z2cndmWzZIVo4QcxwIA8Hco9l544WLyVKmi2/cG61fmSM+8KcobfBf4YYisHJPPhrxjtW/wOUbkVl6MmQcv/RRyXFuhivN4l1pomJNjoQXqk6vpmfYlLTfaD/gEu42CLdeTzbzxkZ+bUV+giywKBgQCkBLhDjZZcxNXGl84pmaW989PydLH6MD3rGBKrg0fFuOLQxYi2VOoqXo+0jHYxFXEIVUT+q0pzwAvswKNQj4HIoc5MilpPDn3gaRtoKxlz6F6GEORevh/J/+bZzcSVsFdnQFswXC/Jpet7/UCc3Qjxq5qJJ8O10OrPMCLwI8RjvQKBgG6GkwjnCScW+fSPEHAMwIq9SDB3CcJswJkeJLZsi75keeKqasgfhw+zFIN/dDvhsKUbzW5v2e4gvnOlcuNz+DyxHOKV1DqNiZ/XtdrmXzUEV3TNvciaLUa04SQf2p54xBzXDWaPZcuz6904qMnSo1LwPcIRMJ9fOLfynfkQ8TEHAoGANUDSKdcuMJNG/PomTtnajdT86KUwbFYR5wjpRT6emSa9ib4dtOE3Tc6sDg08M8W72xL0sh3KS9QmhG8n/4L7+olslj1yl/+CMrftJf0o5QABw576Tl6HmZGfDTWZLSLAVGceV/7rxGlLAc33YNraaS1Bf8zkkXDEqDA3+CSi+0E=";

    /**
     * param值加密公钥
     */
    public static final String paramEncryptPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuoOMKpKwpcx/BEDrILmGFNFb0fJReSOe50gXA/2fkuR+0tJu/9Z2F8RowwFNrD9Ls0HXNSvJHIILS3DPKHBFcL0cp/u0RHSebdntaMqLmj/gQYtvDV8KLww6xuqbN0wHasU/ZBVThqwmA27J5CxRsTZE22GCqDR4CqRFeVOCLtyHbN+hbCnk68wS9newti0i9IvcQQZPEzqFdL3qm2Ge0rJEbKz0+GLfYYo15DbsluXbviA5uTovf8uufPhxq6LL9nFSYTbtPsg5cmpLmwqW9rXEW7NF0d1EBVPHjQvJrih5D+fIB7JOQb/1Xn9Muh2Ai3pawSEaRE0Whm5SpBowjQIDAQAB";
//    public static final String paramEncryptPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6g4wqkrClzH8EQOsguYYU0VvR8lF5I57nSBcD/Z+S5H7S0m7/1nYXxGjDAU2sP0uzQdc1K8kcggtLcM8ocEVwvRyn+7REdJ5t2e1oyouaP+BBi28NXwovDDrG6ps3TAdqxT9kFVOGrCYDbsnkLFGxNkTbYYKoNHgKpEV5U4Iu3Ids36FsKeTrzBL2d7C2LSL0i9xBBk8TOoV0veqbYZ7SskRsrPT4Yt9hijXkNuyW5du+IDm5Oi9/y658+HGrosv2cVJhNu0+yDlyakubCpb2tcRbs0XR3UQFU8eNC8muKHkP58gHsk5Bv/Vef0y6HYCLelrBIRpETRaGblKkGjCNAgMBAAECggEAVlntHRDJJBnnfIqp0X7TavP69NqhidpKCX5A2aIkrReI+AZhSaV7C0ntzsrdsS+k1ptXDdD1zXMP05+o6WoBXE7R45wPO9paNzW8StXriECmjPIHOkOULXAWDl4z+ogCrxYfYTDWePVerBww8KjsMYWUn5UnrsSMBzFC0QcusI6ya+cfxMq1FhbMrSR4OgIZ8PCYdecBq8IZZX74/mZQqBsbCMREB6bAzi1Txl4KVrNQz7LXXX4WI0iJLCawjitHPv9uujev7zz4kR5uv67LRK857siMYPcQUIioHTxZgAGnQwd39yPcDwRYbtMJ7dQTy/Tia2YDNhY9fpk0SbYc6QKBgQDrG8Wx6/cgX/VPWYnb/0EC87E4CrfAh28M/1PykAxXkulqvU6691VqpN6j/V4TCaWDocKpZqoNSqBucojuCInPVAqoUmsqlWSJrbVXO9UVs2t7G564fCpYc/JHZ7UaA7i6tYCJPQ86QBs3QGwQWhqkMx0SJndm1RcxiKgDQgYzOwKBgQDLFllNIxCmIc1B5pexZIFpkQYHxCxwykyVO5UlaF3xWvzqMG26MujVvU9vyNRJrNwdbih8MEvDF7NjXqgJgrNKVpQ+fLHbaJFMqjStYXlZNSmHJSlmH3yKV3F1S+0dRzkGwUedTKNa2q1nX6uFITR5bYCMN5LHzQT2alaG+eje1wKBgCZlZ7jx728THM3zsocCPczMnaGoZnAD7kfyHvSbP9jBfmtXNVdlc0ayXEXt6AI17hj8Pv1JbfYzvNWs0N4G+PKqJ/9rTmMq+LtfaiEv/VHI9oGpdhds98FwVh4BOttfxjh/0dkX5re9pnQ0ijF1daphSpsfOxrJLDuDtOSrULXnAoGBALH0tG2+QzGAPw73E4dS7X9mn+UgRlzTN8YwvqFX0bHTK/m+U/gr8hCQ4VGvpi2k9gAn7fvciha65us1H4Ot7pM+SIp005jSCTgnkR84YZAE4I3Wx28AOi4zL208Cdt09IhxxuIULLRJGFeT4oU2sneQt2qmq8y+XxHZ3lZKGH9jAoGBAMxjbnolza/lrwuKn6LS7jXKgSEkZN7FDzeT/qpn1cqW5yvH3iFVqiJvTkIRQUHWyNT941ezDi83g+fwMx9fe1SVk841L4kXLh5Ps43lnCAAMFvL/Ww2L8Vc/872UDcaGdqVy/QHJ49mhKVp6Qvk/OL4gPwxUXR6Mc+qFHpPC4z3";


    /**
     * 加密算法.
     */
    public static final String KEY_ALGORITHM_KEY = "RSA";
    public static final String KEY_ALGORITHM = "RSA/ECB/PKCS1Padding";


    public static String decryptByPrivateKey(String text) {
        return decryptByPrivateKey(text, returnDecryptPrivateKey);
    }

    /**
     * 私钥解密.
     *
     * @param text             待解密的文本
     * @param privateKeyString 私钥
     * @return 解密后的文本
     */
    public static String decryptByPrivateKey(String text, String privateKeyString) {
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decode(privateKeyString, Base64.DEFAULT));
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_KEY);
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] result = cipher.doFinal(Base64.decode(text, Base64.NO_WRAP));
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encryptByPublicKey(String text) {
        return encryptByPublicKey(text, paramEncryptPublicKey);
    }

    /**
     * 公钥加密.
     *
     * @param text            待加密的文本
     * @param publicKeyString 公钥
     * @return 加密后的文本
     */
    public static String encryptByPublicKey(String text, String publicKeyString) {
        try {
            X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decode(publicKeyString, Base64.DEFAULT));
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_KEY);
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] result = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.encode(result, Base64.NO_WRAP));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 构建RSA密钥对.
     *
     * @return 生成后的公私钥信息
     */
    public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM_KEY);
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        //必须使用NO_WRAP,否则会出现换行符，导致服务端无法解密
        String publicKeyString = new String(Base64.encode(rsaPublicKey.getEncoded(), Base64.NO_WRAP));
        String privateKeyString = new String(Base64.encode(rsaPrivateKey.getEncoded(), Base64.NO_WRAP));
        return new RsaKeyPair(publicKeyString, privateKeyString);
    }

    /**
     * RSA密钥对对象.
     */
//    @Data
//    @NoArgsConstructor
//    @AllArgsConstructor
    public static class RsaKeyPair {
        public RsaKeyPair(String publicKey, String privateKey) {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }

        /**
         * 公钥.
         */
        private String publicKey;

        /**
         * 私钥.
         */
        private String privateKey;

        public String getPublicKey() {
            return publicKey;
        }

        public void setPublicKey(String publicKey) {
            this.publicKey = publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
    }
 
 
 
 
  /*  public static void main(String[] args){
        // 生成公私钥对
        RsaKeyPair keyPair = null;
        try {
            keyPair = generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println("keyPair.getPublicKey() = " + keyPair.getPublicKey());
        System.out.println("keyPair.getPrivateKey() = " + keyPair.getPrivateKey());
        // 公钥加密
        String text = "zhu";
        String encryptStr = RsaUtils.encryptByPublicKey(keyPair.getPublicKey(), text);
        System.out.println("密文 = " + encryptStr);
        // 私钥解密
        String plain = RsaUtils.decryptByPrivateKey(keyPair.getPrivateKey(), encryptStr);
        System.out.println("明文 = " + plain);
    }*/

}